<template>
  <div class="app-container">

    <div class="total-layout">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="total-frame">
            <img :src="img_home_order" class="total-icon">
            <div class="total-title">今日订单总数</div>
            <div class="total-value">{{dashboardData.totalStatistics.todayOrderCount}}</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="total-frame">
            <img :src="img_home_today_amount" class="total-icon">
            <div class="total-title">今日销售总额</div>
            <div class="total-value">￥{{dashboardData.totalStatistics.todaySalesAmount.toFixed(2)}}</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="total-frame">
            <img :src="img_home_yesterday_amount" class="total-icon">
            <div class="total-title">昨日销售总额</div>
            <div class="total-value">￥{{dashboardData.totalStatistics.yesterdaySalesAmount.toFixed(2)}}</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="total-frame">
            <div class="cache-refresh-icon">
              <i class="el-icon-refresh"></i>
            </div>
            <div class="total-title">清除统计数据缓存</div>
            <div class="total-value">
              <el-button type="primary" size="small" @click="handleRefreshCache">立即刷新</el-button>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="un-handle-layout">
      <div class="layout-title">待处理事务</div>
      <div class="un-handle-content">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="un-handle-item">
              <span class="font-medium">待付款订单</span>
              <span style="float: right" class="color-danger">({{dashboardData.pendingTasks.unpaidOrderCount}})</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="un-handle-item">
              <span class="font-medium">已完成订单</span>
              <span style="float: right" class="color-danger">({{dashboardData.pendingTasks.completedOrderCount}})</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="un-handle-item">
              <span class="font-medium">待确认收货订单</span>
              <span style="float: right" class="color-danger">({{dashboardData.pendingTasks.pendingReceiveOrderCount}})</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="un-handle-item">
              <span class="font-medium">待发货订单</span>
              <span style="float: right" class="color-danger">({{dashboardData.pendingTasks.pendingDeliveryOrderCount}})</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="un-handle-item">
              <span class="font-medium">新缺货登记</span>
              <span style="float: right" class="color-danger">({{dashboardData.pendingTasks.newOutOfStockCount}})</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="un-handle-item">
              <span class="font-medium">待处理退款申请</span>
              <span style="float: right" class="color-danger">({{dashboardData.pendingTasks.pendingRefundCount}})</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="un-handle-item">
              <span class="font-medium">已发货订单</span>
              <span style="float: right" class="color-danger">({{dashboardData.pendingTasks.deliveredOrderCount}})</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="un-handle-item">
              <span class="font-medium">待处理退货订单</span>
              <span style="float: right" class="color-danger">({{dashboardData.pendingTasks.pendingReturnCount}})</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="un-handle-item">
              <span class="font-medium">广告位即将到期</span>
              <span style="float: right" class="color-danger">({{dashboardData.pendingTasks.expiringAdsCount}})</span>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <div class="overview-layout">
      <el-row :gutter="20">
        <el-col :span="12">
          <div class="out-border">
            <div class="layout-title">商品总览</div>
            <div style="padding: 40px">
              <el-row>
                <el-col :span="6" class="color-danger overview-item-value">{{dashboardData.productOverview.offShelfCount}}</el-col>
                <el-col :span="6" class="color-danger overview-item-value">{{dashboardData.productOverview.onShelfCount}}</el-col>
                <el-col :span="6" class="color-danger overview-item-value">{{dashboardData.productOverview.lowStockCount}}</el-col>
                <el-col :span="6" class="color-danger overview-item-value">{{dashboardData.productOverview.totalCount}}</el-col>
              </el-row>
              <el-row class="font-medium">
                <el-col :span="6" class="overview-item-title">已下架</el-col>
                <el-col :span="6" class="overview-item-title">已上架</el-col>
                <el-col :span="6" class="overview-item-title">库存紧张</el-col>
                <el-col :span="6" class="overview-item-title">全部商品</el-col>
              </el-row>
            </div>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="out-border">
            <div class="layout-title">用户总览</div>
            <div style="padding: 40px">
              <el-row>
                <el-col :span="6" class="color-danger overview-item-value">{{dashboardData.userOverview.todayNewCount}}</el-col>
                <el-col :span="6" class="color-danger overview-item-value">{{dashboardData.userOverview.yesterdayNewCount}}</el-col>
                <el-col :span="6" class="color-danger overview-item-value">{{dashboardData.userOverview.monthNewCount}}</el-col>
                <el-col :span="6" class="color-danger overview-item-value">{{dashboardData.userOverview.totalCount}}</el-col>
              </el-row>
              <el-row class="font-medium">
                <el-col :span="6" class="overview-item-title">今日新增</el-col>
                <el-col :span="6" class="overview-item-title">昨日新增</el-col>
                <el-col :span="6" class="overview-item-title">本月新增</el-col>
                <el-col :span="6" class="overview-item-title">会员总数</el-col>
              </el-row>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="statistics-layout">
      <div class="layout-title">订单统计</div>
      <el-row>
        <el-col :span="4">
          <div style="padding: 20px">
            <div>
              <div style="color: #909399;font-size: 14px">本月订单总数</div>
              <div style="color: #606266;font-size: 24px;padding: 10px 0">{{dashboardData.orderStatistics.monthOrderCount}}</div>
              <div>
                <span :class="dashboardData.orderStatistics.monthOrderCountGrowth >= 0 ? 'color-success' : 'color-danger'" style="font-size: 14px">
                  {{dashboardData.orderStatistics.monthOrderCountGrowth >= 0 ? '+' : ''}}{{dashboardData.orderStatistics.monthOrderCountGrowth}}%
                </span>
                <span style="color: #C0C4CC;font-size: 14px">同比上月</span>
              </div>
            </div>
            <div style="margin-top: 20px;">
              <div style="color: #909399;font-size: 14px">本周订单总数</div>
              <div style="color: #606266;font-size: 24px;padding: 10px 0">{{dashboardData.orderStatistics.weekOrderCount}}</div>
              <div>
                <span :class="dashboardData.orderStatistics.weekOrderCountGrowth >= 0 ? 'color-success' : 'color-danger'" style="font-size: 14px">
                  {{dashboardData.orderStatistics.weekOrderCountGrowth >= 0 ? '+' : ''}}{{dashboardData.orderStatistics.weekOrderCountGrowth}}%
                </span>
                <span style="color: #C0C4CC;font-size: 14px">同比上周</span>
              </div>
            </div>
            <div style="margin-top: 20px;">
              <div style="color: #909399;font-size: 14px">本月销售总额</div>
              <div style="color: #606266;font-size: 24px;padding: 10px 0">{{dashboardData.orderStatistics.monthSalesAmount}}</div>
              <div>
                <span :class="dashboardData.orderStatistics.monthSalesAmountGrowth >= 0 ? 'color-success' : 'color-danger'" style="font-size: 14px">
                  {{dashboardData.orderStatistics.monthSalesAmountGrowth >= 0 ? '+' : ''}}{{dashboardData.orderStatistics.monthSalesAmountGrowth}}%
                </span>
                <span style="color: #C0C4CC;font-size: 14px">同比上月</span>
              </div>
            </div>
            <div style="margin-top: 20px;">
              <div style="color: #909399;font-size: 14px">本周销售总额</div>
              <div style="color: #606266;font-size: 24px;padding: 10px 0">{{dashboardData.orderStatistics.weekSalesAmount}}</div>
              <div>
                <span :class="dashboardData.orderStatistics.weekSalesAmountGrowth >= 0 ? 'color-success' : 'color-danger'" style="font-size: 14px">
                  {{dashboardData.orderStatistics.weekSalesAmountGrowth >= 0 ? '+' : ''}}{{dashboardData.orderStatistics.weekSalesAmountGrowth}}%
                </span>
                <span style="color: #C0C4CC;font-size: 14px">同比上周</span>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="20">
          <div style="padding: 10px;border-left:1px solid #DCDFE6">
            <el-date-picker
              style="float: right;z-index: 1"
              size="small"
              v-model="orderCountDate"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="handleDateChange"
              :picker-options="pickerOptions">
            </el-date-picker>
            <div>
              <ve-line
                :data="chartData"
                :legend-visible="false"
                :loading="loading"
                :data-empty="dataEmpty"
                :settings="chartSettings"></ve-line>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
  import {str2Date} from '@/utils/date';
  import img_home_order from '@/assets/images/home_order.png';
  import img_home_today_amount from '@/assets/images/home_today_amount.png';
  import img_home_yesterday_amount from '@/assets/images/home_yesterday_amount.png';
  import {getStatistics, getOrderChart, refreshDashboardCache} from '@/api/dashboard';
  
  export default {
    name: 'home',
    data() {
      return {
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        orderCountDate: '',
        chartSettings: {
          xAxisType: 'time',
          area:true,
          axisSite: { right: ['orderAmount']},
          labelMap: {'orderCount': '订单数量', 'orderAmount': '订单金额'}
        },
        chartData: {
          columns: [],
          rows: []
        },
        loading: false,
        dataEmpty: false,
        img_home_order,
        img_home_today_amount,
        img_home_yesterday_amount,
        // 仪表盘数据
        dashboardData: {
          totalStatistics: {
            todayOrderCount: 0,
            todaySalesAmount: 0,
            yesterdaySalesAmount: 0
          },
          pendingTasks: {
            unpaidOrderCount: 0,
            completedOrderCount: 0,
            pendingReceiveOrderCount: 0,
            pendingDeliveryOrderCount: 0,
            newOutOfStockCount: 0,
            pendingRefundCount: 0,
            deliveredOrderCount: 0,
            pendingReturnCount: 0,
            expiringAdsCount: 0
          },
          productOverview: {
            offShelfCount: 0,
            onShelfCount: 0,
            lowStockCount: 0,
            totalCount: 0
          },
          userOverview: {
            todayNewCount: 0,
            yesterdayNewCount: 0,
            monthNewCount: 0,
            totalCount: 0
          },
          orderStatistics: {
            monthOrderCount: 0,
            monthOrderCountGrowth: 0,
            weekOrderCount: 0,
            weekOrderCountGrowth: 0,
            monthSalesAmount: 0,
            monthSalesAmountGrowth: 0,
            weekSalesAmount: 0,
            weekSalesAmountGrowth: 0
          }
        }
      }
    },
    created(){
      this.initOrderCountDate();
      this.loadStatistics();
      this.getData();
    },
    methods:{
      // 刷新缓存
      handleRefreshCache() {
        this.$confirm('此操作将清除统计数据缓存, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true;
          refreshDashboardCache().then(response => {
            this.$message({
              type: 'success',
              message: '缓存清除成功!'
            });
            // 重新加载数据
            this.loadStatistics();
            this.getData();
          }).catch(() => {
            this.$message({
              type: 'error',
              message: '缓存清除失败'
            });
          }).finally(() => {
            this.loading = false;
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消清除缓存'
          });
        });
      },
      // 加载统计数据
      loadStatistics() {
        this.loading = true;
        getStatistics().then(response => {
          this.dashboardData = response.data;
          this.loading = false;
        }).catch(() => {
          this.loading = false;
        });
      },
      handleDateChange(){
        this.getData();
      },
      initOrderCountDate(){
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
        this.orderCountDate = [start, end];
      },
      getData(){
        this.loading = true;
        this.dataEmpty = false;
        
        // 准备请求参数
        const params = {
          startDate: this.formatDate(this.orderCountDate[0]),
          endDate: this.formatDate(this.orderCountDate[1])
        };
        
        getOrderChart(params).then(response => {
          this.chartData = response.data;
          this.loading = false;
          if (this.chartData.rows.length === 0) {
            this.dataEmpty = true;
          }
        }).catch(() => {
          this.loading = false;
          this.dataEmpty = true;
        });
      },
      // 格式化日期为 yyyy-MM-dd
      formatDate(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      }
    }
  }
</script>

<style scoped>
  .app-container {
    margin-top: 40px;
    margin-left: 120px;
    margin-right: 120px;
  }

  .address-layout {
  }

  .total-layout {
    margin-top: 20px;
  }

  .total-frame {
    border: 1px solid #DCDFE6;
    padding: 20px;
    height: 100px;
  }

  .total-icon {
    color: #409EFF;
    width: 60px;
    height: 60px;
  }

  .cache-refresh-icon {
    color: #409EFF;
    font-size: 60px;
    width: 60px;
    height: 60px;
    text-align: center;
  }

  .total-title {
    position: relative;
    font-size: 16px;
    color: #909399;
    left: 70px;
    top: -50px;
  }

  .total-value {
    position: relative;
    font-size: 18px;
    color: #606266;
    left: 70px;
    top: -40px;
  }

  .un-handle-layout {
    margin-top: 20px;
    border: 1px solid #DCDFE6;
  }

  .layout-title {
    color: #606266;
    padding: 15px 20px;
    background: #F2F6FC;
    font-weight: bold;
  }

  .un-handle-content {
    padding: 20px 40px;
  }

  .un-handle-item {
    border-bottom: 1px solid #EBEEF5;
    padding: 10px;
  }

  .overview-layout {
    margin-top: 20px;
  }

  .overview-item-value {
    font-size: 24px;
    text-align: center;
  }

  .overview-item-title {
    margin-top: 10px;
    text-align: center;
  }

  .out-border {
    border: 1px solid #DCDFE6;
  }

  .statistics-layout {
    margin-top: 20px;
    border: 1px solid #DCDFE6;
  }
  .mine-layout {
    position: absolute;
    right: 140px;
    top: 107px;
    width: 250px;
    height: 235px;
  }
  .address-content{
    padding: 20px;
    font-size: 18px
  }
</style>
